package com.sansi.bleFloodlight.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.a1anwang.okble.client.scan.BLEScanResult;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import com.example.blelibrary.ble.BleCommand;


import com.my.httpapi.api.annotation.Layout;
import com.my.httpapi.api.baseView.BaseActivity;
import com.sansi.bleFloodlight.R;
import com.sansi.bleFloodlight.adapter.ConnectLightAdapter;

import com.sansi.bleFloodlight.ble.BleManageUtils;
import com.sansi.bleFloodlight.ble.bleInterface.BleManageListener;

import com.sansi.bleFloodlight.ble.bleInterface.IBleManage;
import com.sansi.bleFloodlight.db.TableDevice;
import com.sansi.bleFloodlight.model.HomeLightEvent;
import com.sansi.bleFloodlight.utils.ActivityUtils;
import com.sansi.bleFloodlight.utils.MMKVUtils;
import com.sansi.bleFloodlight.utils.RouterPath;
import com.sansi.bleFloodlight.view.CustomDialog;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

@Layout(R.layout.layout_activity_connect)
@Route(path = RouterPath.bleConnectPath)
public class BleConnectActivity extends BaseActivity implements BleManageListener {

    private ImageView ivClosed;
    private View llConnectFinish;
    private TextView tvName, tvDescribe, btnOk, btnFail;
    private RecyclerView recyclerView;
    private ConnectLightAdapter connectLightAdapter;

    private List<Integer> listStatus = new ArrayList<>();//0-loading  1-sucess  2-fail

    private int sucessCount = 0;
    private int failCount = 0;

    private HandlerThread handlerThread;
    private Handler workHandler;
    public static final int INT_CONNECT = 0;
    public static final int INT_BIND = 1;
    public static final int SEND_BIND = 2;
    private int devicePosition = 0;//第几个设备
    private BLEScanResult searchResult;
    private int int_write = -1;// 0-写入初始化netkey  1-绑定设备

    private IBleManage iBleManage;

    @Autowired
    public ArrayList<BLEScanResult> deviceList;

    private Context context;

    @Override
    protected void initView() {
        context = this;
        ARouter.getInstance().inject(this);
        ivClosed = findViewById(R.id.iv_closed);
        llConnectFinish = findViewById(R.id.ll_connect_finish);
        tvName = findViewById(R.id.tv_name);
        tvDescribe = findViewById(R.id.tv_describe);
        recyclerView = findViewById(R.id.recycler_view);
        btnOk = findViewById(R.id.btn_ok);
        btnFail = findViewById(R.id.btn_fail);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        iBleManage = new BleManageUtils(this, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        connectLightAdapter = new ConnectLightAdapter();
        recyclerView.setAdapter(connectLightAdapter);
        createData();
        ivClosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new HomeLightEvent());
                finish();
            }
        });
        btnFail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RouterPath.gotoBleConnectFailPath();
            }
        });
        handlerThread = new HandlerThread("bindDevice");
        handlerThread.start();
        workHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case INT_CONNECT:
                        if (deviceList.size() > devicePosition) {
                            //有需要连接的设备
                            searchResult = deviceList.get(devicePosition);
                            iBleManage.setBLEScanResult(searchResult);
                            iBleManage.connect(false);
                        }
                        break;
                    case INT_BIND:
                        int_write = 0;
                        iBleManage.writeData(BleCommand.getDefaultNetkeyData());
                        break;
                    case SEND_BIND:
                        int_write = 1;
                        byte[] bytes3 = ActivityUtils.getByte();
                        byte[] data = BleCommand.getAddDeviceData(ActivityUtils.getLocalNetKey(), 16, bytes3, 2);
                        iBleManage.writeData(data);
                        break;
                }
            }
        };
        message_init_connect();
    }

    @Override
    protected void destory() {
        if (handlerThread != null)
            handlerThread.quit();
        if (iBleManage != null)
            iBleManage.disConnectAll();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return false;
    }

    @Override
    protected boolean showLeftArrow() {
        return false;
    }

    private void showDialog() {
        new CustomDialog.Builder(this)
                .setTitle("Do you want to quit adding?")
                .setMessage("Adding a successful device will not affect you")
                .setPositiveButton("QUIT", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create().show();
    }

    private void message_init_connect() {
        Message msg = Message.obtain();
        msg.what = INT_CONNECT;
        workHandler.sendMessage(msg);
    }

    private void message_init_bind() {
        Message msg = Message.obtain();
        msg.what = INT_BIND;
        workHandler.sendMessage(msg);
    }

    private void message_send_bind() {
        Message msg = Message.obtain();
        msg.what = SEND_BIND;
        workHandler.sendMessage(msg);
    }

    private void updateSucessUI() {
        if (devicePosition >= listStatus.size()) return;
        sucessCount++;
        tvName.setText("complete");
        tvDescribe.setText(sucessCount + "success   " + failCount + "fail");
        llConnectFinish.setVisibility(View.VISIBLE);
        listStatus.set(devicePosition, 1);
        connectLightAdapter.notifyItemChanged(devicePosition);
        //保存设备相关信息
        TableDevice tableDevice = new TableDevice();
        tableDevice.setMac(searchResult.getMacAddress());
        //保存单播地址
        String address = MMKV.defaultMMKV().decodeString(MMKVUtils.ADDRESS);
        tableDevice.setUnicast_address(address);
        tableDevice.save();
        //连接下一个设备
        devicePosition++;
        message_init_connect();
    }

    private void updateFailUI() {
        if (devicePosition >= listStatus.size()) return;
        failCount++;
        tvName.setText("complete");
        tvDescribe.setText(sucessCount + "success   " + failCount + "fail");
        llConnectFinish.setVisibility(View.VISIBLE);
        listStatus.set(devicePosition, 2);
        connectLightAdapter.notifyItemChanged(devicePosition);
        //连接下一个设备
        devicePosition++;
        message_init_connect();
    }

    private void createData() {
        for (int i = 0; i < deviceList.size(); i++) {
            listStatus.add(0);
        }
        connectLightAdapter.setNewData(deviceList, listStatus);
    }

    @Override
    public void openNotify() {
        if (context == null) return;
        message_init_bind();
    }

    @Override
    public void onDisconnected() {
        if (context == null) return;
        updateFailUI();
    }

    @Override
    public void onReceivedValue(String uuid, int code,String value) {
        if (context == null) return;
        if (int_write == 0 && code==BleManageUtils.SUCESS) {
            message_send_bind();
        } else if (int_write == 1 && code==BleManageUtils.SUCESS) {
            //保存设备
            updateSucessUI();
        }
    }
}
